<!--客户对账单-->
<template>
  <div class="customer-statement-container">
    <!-- 筛选区域 -->
    <div class="controls-section">
      <button class="btn-new" @click="openCreateModal">新建对账单</button>
      <div class="filters">
        <div class="filter-item">
          <label>对账单号</label>
          <input type="text" v-model="query.recoCode" placeholder="请输入对账单号">
        </div>
        <div class="filter-item">
          <label>对账状态</label>
          <select v-model="query.status">
            <option value="">全部</option>
            <option :value="0">待对账</option>
            <option :value="1">部分对账</option>
            <option :value="2">全部对账</option>
          </select>
        </div>
      </div>
      <div class="actions">
        <button class="btn-primary" @click="search">搜索</button>
        <button class="btn-secondary" @click="reset">重置</button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="allSelected"></th>
            <th>对账单号</th>
            <th>对账状态</th>
            <th>客户</th>
            <th>账单创建日</th>
            <th>对账起始/终止日</th>
            <th>本期应收</th>
            <th>本期待收</th>
            <th>本期已收</th>
            <th>财务人员</th>
<!--            <th>操作</th>-->

          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in statements" :key="item.recoId">
            <td><input type="checkbox" v-model="item.selected"></td>
            <td class="link-style" @click="viewDetail(item)">{{ item.recoCode }}</td>
            <td>
              <span :class="getStatusClass(item.status)" @click="toggleStatus(item)">
                {{ getStatusText(item.status) }}
              </span>
            </td>
            <td>{{ item.customerName || item.customerId }}</td>
            <td>{{ formatDate(item.createDate) }}</td>
            <td>{{ formatDate(item.createDate) }} / {{ formatDate(item.endDate) }}</td>
            <td>{{ formatMoney(item.currentReceivable) }}</td>
            <td>{{ formatMoney(item.currentToReceive) }}</td>
            <td>{{ formatMoney(item.currentReceived) }}</td>
            <td>{{ item.financialStaff || '-' }}</td>
<!--            <td>-->
<!--              <button class="btn-link" @click="viewDetailsList(item)">查看明细</button>-->
<!--            </td>-->

          </tr>
        </tbody>
      </table>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="allSelected">
        <label>全选</label>
        <button class="btn-secondary">导出</button>
      </div>
      <div class="pagination">
        <button @click="prevPage" :disabled="query.pageNum <= 1">&lt;</button>
        <button
          v-for="page in pageNumbers"
          :key="page"
          :class="{ active: page === query.pageNum }"
          @click="goToPage(page)"
        >
          {{ page }}
        </button>
        <button @click="nextPage" :disabled="query.pageNum >= totalPages">&gt;</button>
        <select v-model="query.pageSize" @change="onPageSizeChange">
          <option value="5">5条/页</option>
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
        </select>
      </div>
    </div>

    <!-- 新建对账单弹窗 -->
    <div v-if="showCreateModal" class="modal-overlay" @click="closeCreateModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>新建对账单</h3>
          <button class="close-btn" @click="closeCreateModal">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitCreate">
            <div class="form-row">
              <div class="form-group">
                <label>客户 *</label>
                <select v-model="createForm.customerId" required>
                  <option value="">请选择客户</option>
                  <option v-for="customer in customerList" :key="customer.id" :value="customer.id">
                    {{ customer.customerName }} ({{ customer.customerCode }})
                  </option>
                </select>
              </div>
              <div class="form-group">
                <label>对账状态</label>
                <select v-model="createForm.status">
                  <option :value="0">待对账</option>
                  <option :value="1">部分对账</option>
                  <option :value="2">全部对账</option>
                </select>
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>账单起始日期 *</label>
                <input type="date" v-model="createForm.createDate" required>
              </div>
              <div class="form-group">
                <label>账单终止日期 *</label>
                <input type="date" v-model="createForm.endDate" required>
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>应收款</label>
                <input type="number" v-model="createForm.currentReceivable" step="0.01">
              </div>
              <div class="form-group">
                <label>待收款</label>
                <input type="number" v-model="createForm.currentToReceive" step="0.01">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>已收款</label>
                <input type="number" v-model="createForm.currentReceived" step="0.01">
              </div>
              <div class="form-group">
                <label>财务人员</label>
                <input type="text" v-model="createForm.financialStaff">
              </div>
            </div>
            <div class="form-actions">
              <button type="button" class="btn-secondary" @click="closeCreateModal">取消</button>
              <button type="submit" class="btn-primary">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 查看详情抽屉（右侧滑出） -->
    <div v-if="showDetailModal" class="drawer-overlay" @click="closeDetailModal">
      <div class="drawer-content" @click.stop>
        <div class="detail-header">
          <h2>{{ detailData.recoCode }}-对账单详情</h2>
          <button class="close-btn" @click="closeDetailModal">×</button>
        </div>
        <div class="detail-body">
          <div class="detail-section">
            <h3>基本信息</h3>
            <div class="detail-form">
              <div class="form-field">
                <label>对账单号</label>
                <input type="text" :value="detailData.recoCode" readonly>
              </div>
              <div class="form-field">
                <label>客户</label>
                <input type="text" :value="detailData.customerName || detailData.customerId" readonly>
              </div>
              <div class="form-field">
                <label>对账状态</label>
                <input type="text" :value="getStatusText(detailData.status)" readonly>
              </div>
              <div class="form-field">
                <label>创建时间</label>
                <input type="text" :value="formatDate(detailData.createDate)" readonly>
              </div>
            </div>
          </div>
          <div class="detail-section">
            <h3>对账信息</h3>
            <div class="detail-form">
              <div class="form-field">
                <label>账单起始日</label>
                <input type="text" :value="formatDate(detailData.createDate)" readonly>
              </div>
              <div class="form-field">
                <label>账单终止日</label>
                <input type="text" :value="formatDate(detailData.endDate)" readonly>
              </div>
              <div class="form-field">
                <label>本期应收</label>
                <input type="text" :value="formatMoney(detailData.currentReceivable)" readonly>
              </div>
              <div class="form-field">
                <label>本期已收</label>
                <input type="text" :value="formatMoney(detailData.currentReceived)" readonly>
              </div>
              <div class="form-field">
                <label>本期待收</label>
                <input type="text" :value="formatMoney(detailData.currentToReceive)" readonly>
              </div>
              <div class="form-field">
                <label>财务人员</label>
                <input type="text" :value="detailData.financialStaff || '-'" readonly>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { recoPage, recoCreate, recoDetail, recoSetStatus, getCustomerList } from '@/api/finance/reconciliation'
import { ElMessage } from 'element-plus'

export default {
  name: 'CustomerStatement',
  data() {
    return {
      statements: [],
      query: {
        pageNum: 1,
        pageSize: 5,
        recoCode: '',
        status: null,
        createDate: ''
      },
      total: 0,
      totalPages: 0,
      // 新建对账单相关
      showCreateModal: false,
      createForm: {
        customerId: '',
        status: 0,
        createDate: '',
        endDate: '',
        currentReceivable: '',
        currentToReceive: '',
        currentReceived: '',
        financialStaff: ''
      },
      // 查看详情相关
      showDetailModal: false,
      detailData: {},
      customerList: [] // 新增客户列表数据
    };
  },
  computed: {
    allSelected: {
      get() {
        return this.statements.length > 0 && this.statements.every(item => item.selected);
      },
      set(value) {
        this.statements.forEach(item => {
          item.selected = value;
        });
      }
    },
    pageNumbers() {
      const pages = [];
      const start = Math.max(1, this.query.pageNum - 2);
      const end = Math.min(this.totalPages, this.query.pageNum + 2);

      for (let i = start; i <= end; i++) {
        pages.push(i);
      }
      return pages;
    }
  },
  mounted() {
    this.load();
    this.loadCustomerList(); // 在组件挂载时加载客户列表
  },
  methods: {
    async load() {
      try {
        const { data } = await recoPage(this.query);
        const pageData = data?.data;
        if (pageData) {
          this.statements = (pageData.records || []).map(x => ({
            ...x,
            selected: false
          }));
          this.total = pageData.total || 0;
          this.totalPages = pageData.pages || 0;
        }
      } catch (error) {
        console.error('加载数据失败:', error);
        ElMessage.error('加载数据失败');
      }
    },
    search() {
      this.query.pageNum = 1;
      this.load();
    },
    reset() {
      this.query = {
        pageNum: 1,
        pageSize: 10,
        recoCode: '',
        status: null,
        createDate: ''
      };
      this.load();
    },
    prevPage() {
      if (this.query.pageNum > 1) {
        this.query.pageNum--;
        this.load();
      }
    },
    nextPage() {
      if (this.query.pageNum < this.totalPages) {
        this.query.pageNum++;
        this.load();
      }
    },
    goToPage(page) {
      this.query.pageNum = page;
      this.load();
    },
    onPageSizeChange() {
      this.query.pageNum = 1;
      this.load();
    },
    openCreateModal() {
      this.showCreateModal = true;
      this.resetCreateForm();
    },
    closeCreateModal() {
      this.showCreateModal = false;
      this.resetCreateForm();
    },
    resetCreateForm() {
      this.createForm = {
        customerId: '',
        status: 0,
        createDate: '',
        endDate: '',
        currentReceivable: '',
        currentToReceive: '',
        currentReceived: '',
        financialStaff: ''
      };
    },
    async submitCreate() {
      // 表单验证
      if (!this.createForm.customerId) {
        ElMessage.error('请选择客户');
        return;
      }
      if (!this.createForm.createDate) {
        ElMessage.error('请选择账单起始日期');
        return;
      }
      if (!this.createForm.endDate) {
        ElMessage.error('请选择账单终止日期');
        return;
      }
      if (this.createForm.createDate > this.createForm.endDate) {
        ElMessage.error('起始日期不能晚于终止日期');
        return;
      }

      try {
        // 转换数据类型与时间格式
        const toDateTime = (d, isStart) => `${d} ${isStart ? '00:00:00' : '23:59:59'}`;
        const formData = {
          ...this.createForm,
          customerId: Number(this.createForm.customerId),
          status: Number(this.createForm.status),
          createDate: toDateTime(this.createForm.createDate, true),
          endDate: toDateTime(this.createForm.endDate, false),
          currentReceivable: this.createForm.currentReceivable !== '' && this.createForm.currentReceivable != null ? Number(this.createForm.currentReceivable) : null,
          currentToReceive: this.createForm.currentToReceive !== '' && this.createForm.currentToReceive != null ? Number(this.createForm.currentToReceive) : null,
          currentReceived: this.createForm.currentReceived !== '' && this.createForm.currentReceived != null ? Number(this.createForm.currentReceived) : null
        };

        const response = await recoCreate(formData);
        if (response.data.code === 200) {
          ElMessage.success('新建对账单成功');
          this.closeCreateModal();
          this.load();
          // 跳转到明细页（通过Dashboard承载视图）
          const created = response.data.data || {};
          if (created.recoCode) {
            this.$router && this.$router.push({ path: '/dashboard', query: { view: 'CustomerReconciliationDetail', recoCode: created.recoCode } });
          }
        } else {
          ElMessage.error(response.data.msg || '新建失败');
        }
      } catch (error) {
        console.error('新建对账单失败:', error);
        ElMessage.error('新建对账单失败，请稍后重试');
      }
    },
    async viewDetail(item) {
      try {
        const response = await recoDetail(item.recoId);
        if (response.data.code === 200) {
          this.detailData = response.data.data;
          this.showDetailModal = true;
        } else {
          ElMessage.error(response.data.msg || '获取详情失败');
        }
      } catch (error) {
        console.error('获取对账单详情失败:', error);
        ElMessage.error('获取对账单详情失败，请稍后重试');
      }
    },
    closeDetailModal() {
      this.showDetailModal = false;
      this.detailData = {};
    },
    async toggleStatus(item) {
      try {
        const newStatus = (item.status + 1) % 3; // 0->1->2->0
        const response = await recoSetStatus(item.recoId, newStatus);
        if (response.data.code === 200) {
          item.status = newStatus;
          ElMessage.success('状态更新成功');
        } else {
          ElMessage.error(response.data.msg || '状态更新失败');
        }
      } catch (error) {
        console.error('状态更新失败:', error);
        ElMessage.error('状态更新失败，请稍后重试');
      }
    },
    getStatusClass(status) {
      const classes = {
        0: 'status-pending',
        1: 'status-partial',
        2: 'status-complete'
      };
      return classes[status] || 'status-pending';
    },
    getStatusText(status) {
      const texts = {
        0: '待对账',
        1: '部分对账',
        2: '全部对账'
      };
      return texts[status] || '待对账';
    },
    formatDate(date) {
      if (!date) return '-';
      return new Date(date).toLocaleDateString();
    },
    formatMoney(amount) {
      if (!amount) return '0.00';
      return parseFloat(amount).toFixed(2);
    },
    async loadCustomerList() {
      try {
        const response = await getCustomerList();
        if (response.data.code === 200) {
          this.customerList = response.data.data || [];
        } else {
          ElMessage.error(response.data.msg || '加载客户列表失败');
        }
      } catch (error) {
        console.error('加载客户列表失败:', error);
        ElMessage.error('加载客户列表失败，请稍后重试');
      }
    },
    viewDetailsList(item){
      const code = item.recoCode;
      if (this.$router && code) {
        this.$router.push({ path: '/dashboard', query: { view: 'CustomerReconciliationDetail', recoCode: code } });
      }
    }
  }
}
</script>

<style scoped>
.customer-statement-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.controls-section {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  align-items: center;
}

.btn-new {
    background-color: #409eff;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
}

.filters {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
  white-space: nowrap;
}

.filter-item input, .filter-item select {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 150px;
}

.actions {
  margin-left: auto;
}

.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f8f9fa;
}

.link-style {
    color: #409eff;
    cursor: pointer;
}

.status-pending {
  background-color: #fef2f2;
  color: #f56c6c;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
}

.status-partial {
  background-color: #fff7e6;
  color: #e6a23c;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
}

.status-complete {
  background-color: #f0f9ff;
  color: #409eff;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-link {
  background: none;
  border: none;
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.footer-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination select {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 24px 20px;
  border-bottom: 1px solid #ebeef5;
  background: lightskyblue;
  border-radius: 12px 12px 0 0;
}

.modal-header h3 {
  margin: 0;
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.close-btn:hover {
  color: white;
  background-color: rgba(255, 255, 255, 0.1);
}

.modal-body {
  padding: 24px;
  background-color: #fafbfc;
}

.form-tips {
  background-color: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 6px;
  padding: 12px 16px;
  margin-bottom: 20px;
}

.form-tips p {
  margin: 0 0 8px 0;
  color: #0369a1;
  font-weight: 500;
}

.form-tips ul {
  margin: 0;
  padding-left: 20px;
  color: #0369a1;
}

.form-tips li {
  margin-bottom: 4px;
  font-size: 14px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  align-items: flex-start;
}

.form-group {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.form-group label {
  margin-bottom: 8px;
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.form-group input,
.form-group textarea,
.form-group select {
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.form-group select {
  background-color: #fff;
  cursor: pointer;
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
  transform: translateY(-1px);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 32px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.form-actions button {
  padding: 10px 24px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 80px;
}

/* 详情弹窗样式 */
/* 右侧抽屉 */
.drawer-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.35);
  display: flex;
  justify-content: flex-end;
  align-items: stretch;
  z-index: 1000;
}
.drawer-content {
  background: #fff;
  width: 520px;
  max-width: 85vw;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: -2px 0 12px rgba(0,0,0,0.1);
  animation: slideInRight 0.25s ease-out;
}
@keyframes slideInRight { from { transform: translateX(100%);} to { transform: translateX(0);} }

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 24px 20px;
  border-bottom: 1px solid #ebeef5;
  background: #ffffff;
  border-radius: 0;
}

.detail-header h2 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.detail-body {
  padding: 24px;
  background-color: #fafbfc;
}

/* 抽屉右上角关闭按钮与白底适配 */
.close-btn { color: #909399; }
.close-btn:hover { background-color: rgba(0,0,0,0.05); color: #606266; }

.detail-section {
  margin-bottom: 32px;
}

.detail-section h3 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  padding-bottom: 8px;
  border-bottom: 2px solid #409eff;
}

.detail-form {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-field {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-field label {
  font-weight: 500;
  color: #606266;
  font-size: 14px;
}

.form-field input {
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  background-color: #f5f7fa;
  color: #606266;
}

.form-field input:read-only {
  background-color: #f5f7fa;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 16px;
  }

  .modal-content {
    width: 95%;
    margin: 10px;
  }

  .modal-body {
    padding: 16px;
  }

  .detail-form {
    grid-template-columns: 1fr;
  }

  .detail-modal-content {
    width: 98%;
    margin: 10px;
  }
}
</style>
